// JavaScript Document
//Consts
const maxFPS = 30;
const totalResources = 1;
const n = 10; //mänguvälja ruutude arv (alati kasutada dünaamiliselt)
//Global wariables
var canvas = null;
var ctx = null;
var curFPS = 0;
var numFramesDrawn = 0;
var fpsInterval = setInterval(updateFPS, 1000);
var images = {};
var spriteSheets = {};
var grid = 32;
var contentLoaded = false;
var resourcesLoaded = 0;

window.onload = init;

//Camera
camera = {
	scale: 1,
	x: 0,
	y: 0
}

//Mouse
mouse = {
	x: 0,
	y: 0,
	press: false
}

function mouseMove(evt) {
	var obj = canvas;
    var top = 0;
    var left = 0;
    while (obj && obj.tagName != 'BODY') {
        top += obj.offsetTop;
        left += obj.offsetLeft;
        obj = obj.offsetParent;
    }
    // return relative mouse position
    mouse.x = evt.clientX - left + window.pageXOffset;
    mouse.y = evt.clientY - top + window.pageYOffset;
}

function mouseUp(evt) {
	mouse.press = false;
}

function mouseDown(evt) {
	mouse.press = true;
}

var keys = new Array();
var keylock = new Array();
window.addEventListener('keydown', keyDown, true);
window.addEventListener('keyup', keyUp, true);
window.addEventListener('blur', canvasLostFocus, true);

function canvasLostFocus(evt) {
	keys = new Array();
}
function keyDown(evt) {
	keys[evt.keyCode] = true;
}
function keyUp(evt) {
	keys[evt.keyCode] = false;
	keylock[evt.keyCode] = false;
}

function init() {
	canvas = document.getElementById('canvas');
	ctx = canvas.getContext("2d");
	canvas.addEventListener("mousemove", mouseMove, false);
	canvas.addEventListener("mouseup", mouseUp, false);
	canvas.addEventListener("mousedown", mouseDown, false);
	loadContext();
	setInterval(gameLoop, 1000/maxFPS);
}

function loadContext () {
	loadImage("minion_sheet");
	spriteSheets["minion"] = new Spritesheet("minion_sheet");
	spriteSheets["minion"].setSprite("body",0,0,67,104);
	spriteSheets["minion"].setSprite("feet",73,3,27,53);
	spriteSheets["minion"].setSprite("eye",76,59,20,20);
	spriteSheets["minion"].setSprite("closedeye",76,83,20,20);
	spriteSheets["minion"].setSprite("pickaxe",0,104,39,61);
	loadImage("floor_bg");
}

function loadImage(name) {
	images[name] = new Image();
	images[name].onload = function() { 
		resourcesLoaded ++;
		if (resourcesLoaded == totalResources) {
			contentLoaded = true;
		}
	}
	images[name].src = "img/" + name + ".png";
}

function updateFPS() {
	curFPS = numFramesDrawn;
	numFramesDrawn = 0;
}		

function gameLoop() {
	if (contentLoaded) {
		update();
		clear();
		draw();
	} else {
		//drawLoading();
	}
}

function clear() {
	// Store the current transformation matrix
	ctx.save();
	// Use the identity matrix while clearing the canvas
	ctx.setTransform(1, 0, 0, 1, 0, 0);
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	// Restore the transform
	ctx.restore();
}